<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button
          type="text"
          icon="el-icon-view"
          size="small"
          plain
          style="border: 0; background-color: transparent !important"
          @click.stop="handleView(row)"
          v-if="permission.allocationManage_view"
          >详情
        </el-button>
        <!-- <el-button type="text" icon="el-icon-s-promotion" size="small" plain style="border: 0; background-color: transparent !important" @click.stop="handleCreateView(row)">
          生成备料单
        </el-button> -->
        <el-button type="text" icon="el-icon-upload2" size="small" @click.stop="handleWriteBack(row)" :disabled="row.status !== 2" v-if="permission.allocationManage_writeBack"
          >回写
        </el-button>
      </template>
      <template slot-scope="{ row }" slot="sourceType">
        <span>{{ row.sourceType == 'erp' ? 'ERP同步' : 'MES新增' }}</span>
      </template>
    </avue-crud>
    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDialog" v-if="showDialog" custom-class="allocationDialog" width="60%" top="7vh">
      <template v-if="title == '调拨单详情'">
        <div class="common-modal-sub-title">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h1 class="avue-group__title">基本信息</h1>
        </div>
        <avue-form :option="baseOption" v-model="baseForm" ref="form"></avue-form>
        <div class="common-modal-sub-title">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h1 class="avue-group__title">物料明细</h1>
        </div>
      </template>
      <avue-crud
        :option="sheetOption"
        :table-loading="detailLoading"
        :data="sheetData"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="sheetForm"
        ref="addTableCrud"
        :key="timer"
      >
      </avue-crud>
      <div slot="footer" class="avue-dialog__footer" v-if="title == '调拨单详情'">
        <el-button size="small" icon="el-icon-circle-close" @click="showDialog = false">取消</el-button>
        <el-button type="primary" size="small" icon="el-icon-s-promotion" @click="handleCreatePreMaterialList">生成备料单</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getAoPackId, writeBack } from '@/api/warehouse/allocation-manage';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import { title } from 'process';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'ALLOCATION_MANAGE',
      form: {},
      typeObj: {},
      sheetForm: {},
      baseForm: {},
      loading: false,
      detailLoading: false,
      isNone: '', //是否显示修改
      title: '',
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      rowData: {}, //行数据
      selectionList: [],
      sheetId: '',
      showDialog: false,
      data: [],
      sheetData: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        dialogClickModal: false,
        border: true,
        height: 'calc(100vh - 360px)',
        viewBtn: false,
        addBtn: false,
        selection: false,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        indexLabel: '序号',
        menu: true,
        menuWidth: 250,
        columnBtn: false,
        searchSpan: 5,
        column: [
          {
            label: '调拨单据',
            prop: 'transferOrderNo',
            search: true
          },
          {
            label: '业务类型',
            prop: 'transferOrderType',
            type: 'select',
            dicData: [
              {
                label: '直接调拨单',
                value: 'DTO'
              },
              {
                label: '调拨申请单',
                value: 'RFT'
              }
            ]
          },
          {
            label: '状态',
            prop: 'status',
            search: true,
            type: 'select',
            width: 100,
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' },
              { label: '调拨中', value: '5' }
            ]
          },
          {
            label: '数据来源',
            prop: 'sourceType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_source',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '备注',
            prop: 'remark',
            overHidden: true
          }
        ]
      },
      sheetOption: {
        tip: false,
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        dialogClickModal: false,
        height: '400',
        border: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        columnBtn: false,
        cancelBtn: false,
        saveBtn: false,
        selection: false,
        menu: false,
        menuWidth: 100,
        page: false,
        index: false,
        refreshBtn: false,
        expandBtn: false,
        column: [
          {
            label: '调拨单据',
            prop: 'transferOrderNo'
          },
          {
            label: '调拨单行号',
            prop: 'transferOrderLot'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '物料品牌',
            prop: 'partBrand'
          },
          {
            label: '调出仓库',
            prop: 'outWarehouseName'
          },
          { label: '调入仓库', prop: 'inWarehouseName' },
          {
            label: '计划调拨数量',
            prop: 'planQuantity'
          },
          {
            label: '实际调拨数量',
            prop: 'actualQuantity'
          },

          {
            label: '单位',
            prop: 'uom'
          }
        ]
      },
      baseOption: {
        emptyBtn: false,
        submitBtn: false,
        detail: true,
        column: [
          { label: '调拨单据', prop: 'transferOrderNo' },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            width: 100,
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' },
              { label: '调拨中', value: '5' }
            ]
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.allocationManage_view, false)
      };
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 查看模态框
     */
    handleView(row) {
      this.title = '详情';
      this.showDialog = true;
      this.sheetId = row.id;
      this.getListData(row.id);
    },
    /**
     * 获取单据详情
     */
    getListData(id) {
      this.detailLoading = true;
      getDetail(id)
        .then((res) => {
          const data = res.data.data;
          this.sheetData = data.transferOrderDetailList || [];
          // this.sheetData.forEach((item) => {
          //   item.inWarehouseName = data.inWarehouseName;
          //   item.outWarehouseName = data.outWarehouseName;
          // });
        })
        .finally(() => {
          this.detailLoading = false;
        });
    },
    handleCreateView(row) {
      this.title = '调拨单详情';
      this.showDialog = true;
      this.sheetId = row.id;
      this.baseForm = structuredClone(row);
      this.getListData(row.id);
    },
    handleCreatePreMaterialList() {
      this.$message.warning('暂未实现');
      this.showDialog = false;
    },
    /**
     * 回写
     */
    handleWriteBack(row) {
      this.$confirm('手动回写后，此单据不可再执行调拨，是否确认回写?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        writeBack(row.id).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.onLoad(this.page);
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .allocationDialog {
  .el-dialog__body {
    padding: 0 20px 20px;
  }
  .avue-crud__menu {
    display: none;
  }
  .common-modal-sub-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
    margin: 10px 0;
  }
}
</style>
